{# 模板嵌套，方便地使用base.html #}
{% extends 'base.html' %}

{% load static %}
{% load comment_tags %}
{% load like_tags %}

{% block header_extends %}
    <link rel="stylesheet" href="{% static 'blog/blog.css' %}"> 
    <link rel="stylesheet" href="{% static 'blog/highlight.css' %}">
    <script type="text/javascript" src="{% static 'ckeditor/ckeditor-init.js' %}"></script>
    <script type="text/javascript" src="{% static 'ckeditor/ckeditor/ckeditor.js' %}"></script>
{% endblock %}

{# 页面标题 #}
{% block title %}{{ blog.title }}{% endblock %}

{# 页面内容 #}
{% block nav_blog_active %}active{% endblock %}

{% block content %}
<div class="container normal-container">
    <div class="row">
        <div class="col-xs-10 col-xs-offset-1 col-sm-9 col-sm-offset-0">
            <div class="panel panel-default">
                <div class="panel-heading" id="detail_panel_heading">
                    <h1>{{ blog.title }}</h1>
                    <hr />
                    <ul class="blog-info-description">
                        <li>作者：{{ blog.author.get_nickname_or_username }}</li>
                        <li>分类：
                            <a href="{% url 'blogs_with_type' blog.blog_type.pk %}" class="btn btn-info btn-xs">
                            {{ blog.blog_type }}
                            </a>
                        </li>
                        <li>发表日期：{{ blog.create_time|date:"Y-m-d G:i" }}</li>
                        <li>阅读：({{ blog.get_read_num }})</li>
                        <li>评论：({% get_comment_num blog %})</li>
                    </ul>
                </div>
                <div class="panel-body" id="detail_panel_body">
                    <div class="like" id="text_like" onclick="pressLike(this, '{% get_content_type blog %}', {{ blog.pk }})">
                        <div class="like-icon">
                            <span class="glyphicon glyphicon-thumbs-up {% get_like_status blog %}"></span>
                            <span class="glyphicon glyphicon-thumbs-up {% get_like_status blog %}"></span>
                        </div>
                        <span class="{% get_like_status blog %} liked_num">{% get_liked_num blog %}</span>
                        <span class="{% get_like_status blog %}">喜欢</span>
                    </div>
                    <div class="blog-content">{{ blog.content|safe }}</div>
                </div>
                <div class="panel-footer">
                    <div class="blog-more">
                        <p>上一篇：
                            {% if previous_blog %}
                                <a href="{% url 'blog_detail' previous_blog.pk %}">{{ previous_blog.title }}</a> 
                            {% else %}
                                没有了
                            {% endif %}
                        </p>
                        <p>下一篇：
                            {% if next_blog %}
                                <a href="{% url 'blog_detail' next_blog.pk %}">{{ next_blog.title }}</a> 
                            {% else %}
                                没有了
                            {% endif %}
                        </p>
                    </div>
                
                </div>
            </div>
        </div>

        <div class="hidden-xs col-sm-3">
            <div class="panel panel-default" id="blog-toc">
                <div class="panel-heading toc">
                    <h3 class="panel-title">目录</h3>
                </div>
                <div class="panel-body toc">
                    {{ toc|safe }}
                </div>
            </div>
        </div>

        <div class="hidden-xs col-sm-3">
            <div id="return">
                <a href="#navigation">返回顶部</a> 
            </div>
        </div>
    </div>


    <div class="row">
        <div class="col-xs-10 col-xs-offset-1">
            <div class="comment-area">
                <h3 class="comment-area-title">提交评论</h3>
                {% if user.is_authenticated %}
                    {# 用户已经登陆 #}
                    <form action="{% url 'add_comment' %}" method="POST" id="comment_form">
                        <label>{{ user.get_nickname_or_username }}，欢迎评论</label>
                        <div id="reply_content_container">
                            <p id="reply_hint">回复：</p>
                            <div id="reply_content"></div>
                        </div>
                        {% csrf_token %}
                        {% get_comment_form blog as comment_form %}
                        {% for field in comment_form %}
                            {{ field }}
                        {% endfor %}
                        <span id="comment_error" class="text-danger pull-left"></span>
                        <input class="btn btn-primary pull-right" type="submit" value="评论">
                    </form>
                {% else %}
                    {# 用户未登陆 #}
                    <span>请登录后发表评论~</span>
                    <a class="btn btn-primary" href="{% url 'login' %}?from={{ request.get_full_path }}">登录</a>
                    or
                    <a class="btn btn-info" href="{% url 'register' %}?from={{ request.get_full_path }}">注册</a>
                {% endif %}
            </div>

            <div class="comment-area">
                <h3 class="comment-area-title">评论列表</h3>
                <ul id="comment_list">
                    {% get_comment_list blog as comments %}
                    {% for comment in comments %}
                        <li class="comment">
                                <span>{{ comment.user.get_nickname_or_username }}</span>
                                <span>({{ comment.comment_time|date:"Y-m-d G:i:s" }}): </span>
                            <div id="comment_{{ comment.pk }}">
                                <span>{{ comment.text|safe }}</span>
                            </div>
                            <div class="like" onclick="pressLike(this, '{% get_content_type comment %}', {{ comment.pk }})">
                                <span class="glyphicon glyphicon-thumbs-up {% get_like_status comment %}"></span>
                                <span class="{% get_like_status comment %} liked_num">{% get_liked_num comment %}</span>
                            </div>
                            <a href="javascript:reply_comment({{ comment.pk }}, '{{ user.is_authenticated }}')">回复</a>
                            <ul id="comment_{{ comment.pk }}_reply_list">
                                {% for reply in comment.replies.all %}
                                    <li class="reply">
                                            <span>{{ reply.user.get_nickname_or_username }}</span>
                                            <span>({{ reply.comment_time|date:"Y-m-d G:i:s" }}) </span>
                                            <span>回复：{{ reply.reply_user.get_nickname_or_username }}</span>
                                        <div id="comment_{{ reply.pk }}">
                                            <span>{{ reply.text|safe }}</span>
                                        </div>
                                        <div class="like" onclick="pressLike(this, '{% get_content_type reply %}', {{ reply.pk }})">
                                            <span class="glyphicon glyphicon-thumbs-up {% get_like_status reply %}"></span>
                                            <span class="{% get_like_status reply %} liked_num">{% get_liked_num reply %}</span>
                                        </div>
                                        <a href="javascript:reply_comment({{ reply.pk }}, '{{ user.is_authenticated }}')">回复</a>
                                    </li>
                                {% endfor %}
                            </ul>
                        </li>
                    {% empty %}
                    <li id="no_comment">期待你留下第一条评论</li>
                    {% endfor %}
                </ul>
            </div>
        </div> 
        </div>
    </div>
</div>
{% endblock %}

{% block script_extends %}
    <script type="text/javascript">
        String.prototype.format = function(){
            var str = this;
            for(var i=0;i<arguments.length;i++){
                str = str.replace(new RegExp('\\{' + i + '\\}','g'), arguments[i]);
            }
            return str;
        }
        $("#comment_form").submit(function(){
            $("#comment_error").text("");   
            //更新数据到textaera
            CKEDITOR.instances["id_text"].updateElement();
            //判断评论是否为空
            if(CKEDITOR.instances["id_text"].document.getBody().getText().trim()==""){
                $("#comment_error").text("评论内容不能为空");   
                return false;
            }
            // 异步提交
            $.ajax({
                url: "{% url 'add_comment' %}",
                type: 'POST',
                data: $(this).serialize(),
                cache: false,
                success: function(data){
                    if(data['status']=='SUCCESS'){
                        // 插入数据
                        if($("#id_reply_comment_pk").val()=='0'){
                            // 不是回复，是评论
                            var comment_html = '<li class="comment"> <span>{0}</span>' + 
                                    '<span>({1}): </span>' + 
                                    '<div id="comment_{2}">' + 
                                        '<span>{4}</span>' + 
                                    '</div>' + 
                                    '<div class="like" onclick="pressLike(this, \'{3}\', {2})">' + 
                                        '<span class="glyphicon glyphicon-thumbs-up"></span> ' + 
                                        '<span class="liked_num">0</span>' + 
                                    '</div>' +
                                    '<a href="javascript:reply_comment({2}, \'True\')">回复</a>' +
                                    '<ul id="comment_{2}_reply_list"></ul></li>'

                            comment_html = comment_html.format(data['username'], data['comment_time'],
                                                data['pk'], data['content_type'], data['text']);
                            $("#comment_list").prepend(comment_html);
                        }else{
                            // 是回复
                            var reply_html = '<li class="reply">' +
                                            '<span>{0}</span>' + 
                                            '<span>({1}) </span>' + 
                                            '<span>回复：{3}</span>' + 
                                        '<div id="comment_{2}">' + 
                                            '<span>{5}</span>' + 
                                        '</div>' + 
                                        '<div class="like" onclick="pressLike(this, \'{4}\', {2})">' + 
                                            '<span class="glyphicon glyphicon-thumbs-up"></span> ' + 
                                            '<span class="liked_num">0</span>' + 
                                        '</div>' + 
                                        '<a href="javascript:reply_comment({2}, \'True\')">回复</a>'+
                                        '</li>'
                            reply_html = reply_html.format(data['username'], data['comment_time'],
                                                data['pk'], data['reply_username'], data['content_type'], data['text']);
                            $("#comment_" + data['root_pk'] + "_reply_list").append(reply_html);
                        }
                        // 清除掉没有评论时显示的内容
                        $("#no_comment").remove();
                        // 清除输入
                        CKEDITOR.instances["id_text"].setData('');
                        // 提交成功后，标记回复对象pk=0，同时隐藏表示回复的内容
                        $("#id_reply_comment_pk").val('0');
                        $("#reply_content_container").hide();
                        $("#comment_error").text("评论成功");
                    }else{
                        // 显示错误信息
                        $("#comment_error").text(data["message"]);
                    }
                },
                error: function(xhr){
                    console.log(xhr);
                }
            });
            return false;
        });

        function reply_comment(reply_comment_id, is_login){
            console.log(is_login);
            if(is_login == 'True'){
                $("#id_reply_comment_pk").val(reply_comment_id);
                $('html').animate({scrollTop: $("#comment_form").offset().top - 60 }, 300, function(){
                    CKEDITOR.instances["id_text"].focus();
                    $("#reply_content").html($("#comment_"+reply_comment_id).html());
                    $("#reply_content_container").show();
                });
            }else{
                $('#login_modal').modal('show');
            }
        }

        function pressLike(label, content_type, object_id){
            var pressed = label.getElementsByClassName('active').length > 0;
            $.ajax({
                url : "{% url 'press_like' %}",
                type : 'GET',
                data : {
                    content_type: content_type,
                    object_id: object_id,
                    pressed: pressed
                },
                cache : false,
                success : function(data){
                    console.log(data);
                    if(data['status']=='SUCCESS'){
                        // 数目修改
                        $(label.getElementsByClassName("liked_num")).text(data['liked_num']);
                        var active_elements = label.children;
                        console.log(active_elements);
                        if(pressed){
                            // 之前是按下，现在是消除
                            // 取消点赞状态
                            for(var i=0;i<active_elements.length;++i){
                                $(active_elements[i]).removeClass('active');
                            }
                        }
                        else{
                            // 之前未按下，现在按下
                            for(var i=0;i<active_elements.length;++i){
                                $(active_elements[i]).addClass('active');
                            }
                        }
                    }else{
                        console.log(data['code']==400);
                        if(data['code']==400){
                            $('#login_modal').modal('show');
                        }else{
                            alert(data['message']);
                        }
                    }
                },
                error : function(xhr){
                    console.log(xhr);
                }
            });
        }

    </script>
{% endblock %}